package org.monkey.common.constant.util;

import cn.hutool.core.util.StrUtil;
import java.util.HashMap;
import org.monkey.common.constant.config.CommonConstant;
import org.monkey.common.constant.entity.UrlEntity;


/**
 * url解析工具
 *
 * @author LiTing
 * @date 2021/2/26 11:12
 */
public class UrlUtil {

  /**
   * 解析url
   *
   * @param url
   * @return
   */
  public static UrlEntity parse(String url) {
    UrlEntity entity = new UrlEntity();
    if (url == null) {
      return entity;
    }
    url = url.trim();
    if (CommonConstant.EMPTY_STRING.equals(url)) {
      return entity;
    }
    String[] urlParts = url.split("\\?");
    entity.baseUrl = urlParts[0];
    // 没有参数
    if (urlParts.length == 1) {
      return entity;
    }
    // 有参数
    String[] params = urlParts[1].split("&");
    entity.params = new HashMap<>(params.length);
    for (String param : params) {
      if (StrUtil.isNotBlank(param)) {
        String[] keyValue = param.split("=");
        if (keyValue.length == 2) {
          entity.params.put(keyValue[0], keyValue[1]);
        }
      }
    }

    return entity;
  }
}

